import React, {Component} from 'react'
import {Modal, Button,message,Table,Input,Checkbox,Icon,InputNumber,Popconfirm } from 'antd'
import {WeaDialog,WeaRightMenu,WeaTab,WeaInput,WeaSearchGroup } from 'ecCom';
import ColorPanel from '../comp/colorPanel'
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

class SetTagModal extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            isShowPanel:false,
            tagValue:"",
            bgcolor:"",
            color:"",
            index:0,
            isrefresh:1,
            dataSource: props.data || []
        }
        this.columns = [{
                title: getLabel(81323,'标签名称'),
                dataIndex: 'title',
                width: '30%',
                render:(text,record,index)=>{
                    return <WeaInput viewAttr="3" value={`${record.title}`} onBlur={value => this.onTitleChange(value,index)} />
            }
            }, {
                title: getLabel(31214,'标签颜色'),
                dataIndex: 'labelColor',
                width: '30%',
                render: (text, record, index) => {
                    return  <div>
                        <span style={{background:`${record.labelColor}`,color:`${record.textColor}`,padding:"2px 3px"}}>
                            {record.title}
                        </span>
                        <Icon type="edit"  style={{marginLeft:"5px"}} onClick={()=>this.showColorPanel(record.title,record.labelColor,record.textColor,index)}/>
                    </div>
                },
            }, {
                title: 'TAB'+getLabel(89,"显示"),
                dataIndex: 'isUsed',
                width: '20%',
                render: (text, record, index) => {
                    return  <Checkbox defaultChecked={Number(`${record.isUsed}`)} onChange={()=>this.setTabShow(index)}/>
                },
            }, {
                title: getLabel(88,'顺序'),
                dataIndex: 'labelOrder',
                render: (text, record, index) => {
                    return <InputNumber min={0} max={99999} defaultValue={`${record.labelOrder}`} onChange={(value )=>this.setOrder(value,index)}/>
                },
                width:"10%"
            },{
                title: getLabel(104,'操作'),
                dataIndex: 'operation',
                width:"10%",
                render: (text, record, index) => {
                    return (
                    this.state.dataSource.length >0 ?
                    (
                        <Popconfirm title={getLabel(83600,"您确认要删除吗？")} onConfirm={() =>this.onDelete(index)}>
                            <a>{getLabel(91,"删除")}</a>
                        </Popconfirm>
                    ) : null
                    );
                },
        }];
    }
    set visible(value) {
        this.setState({visible: value})
    }

     componentDidMount() {
		const { dataSource = [] } = this.state;
		this.setState({dataSource: this.addKeytoDatas(dataSource)})
    }
    componentWillReceiveProps(nextProps,nextState) {
		const {  data = [] } = this.props;
		const _datas = nextProps.data || [];
		JSON.stringify(data) !== JSON.stringify(_datas) && this.setState({dataSource: this.addKeytoDatas(_datas)});
	}
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    onDelete = (index) => {
        const {contentStore,type} = this.props;
        const {dataSource} = this.state;
        let _dataSource = [].concat(dataSource);

        if(Number(_dataSource[index].id)){
            contentStore.crmTagDelete({id:dataSource[index].id,type:type});
        }
        _dataSource.splice(index, 1);
        this.setState({ dataSource:_dataSource });
    }
    onAdd = () => {
        const {  dataSource } = this.state;
        const len = dataSource.length;
        const order = (function(){
            if(len){
                let orderMax = Number(dataSource[0].labelOrder);
                for(let i=1;i<len;i++){
                    if(Number(dataSource[i].labelOrder) > orderMax){
                        orderMax = Number(dataSource[i].labelOrder);
                    }
                }
                return orderMax
            }else{
                return -1
            }
        })();
        const newData = {  
            key: len+1,
            title: '',
            isUsed: "0",
            labelOrder:  order+1,
            labelColor:"#8CC76D",
            "textColor": "#ffffff",
        };
        this.setState({dataSource: [...dataSource, newData]});
    }
    onTitleChange=(value,index)=>{
        const {dataSource,isrefresh} = this.state;
        let _dataSource =  [].concat(dataSource);
        const isHas = (function(){ 
            for(let i=0; i<_dataSource.length; i++){
                if(_dataSource[i].title == value && i != index){
                    Modal.warning({
                        title: getLabel(15172,"系统提示"),
                        content: getLabel(25434,'标签名已存在!'),
                        okText:getLabel(33703,"确定"),
                    });
                    return false
                }
            }
            return true
        })();
        if(isHas){_dataSource[index].title = value; }
        this.setState({dataSource:_dataSource,isShowPanel:false,isrefresh:isrefresh+1});
    }
    setTabShow=(index)=>{
        const {dataSource,} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].isUsed = Number(_dataSource[index].isUsed) ? "0":"1";
        this.setState({dataSource:_dataSource});
    }
    setOrder=(val,index)=>{
        const {dataSource,} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].labelOrder = val;
        this.setState({dataSource:_dataSource});
    }
    render() {
        let {visible,dataSource,isShowPanel,tagValue,bgcolor,color,isrefresh} = this.state;
        const {data} = this.props;
        const columns = this.columns;
        return (
            <WeaDialog
                style={{width: 800,height:400}}
                visible={visible}
                title={getLabel(30884,'标签设置')}
                icon="icon-coms-crm"
                iconBgcolor="#96358a"
                buttons={[
                    <Button type="primary"  onClick={this.doSave} >{getLabel(86,"保存")}</Button>,
                    <Button onClick={() => this.setVisible(false)}>{getLabel(309,"关闭")}</Button>
                ]}
                onCancel={() => this.setVisible(false)}
            >
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                   <WeaTab
                        buttons={this.getButtons()}
                        selectedKey={""}
                    />
                    <div style={{height:348,overflow:'auto',padding:"0"}} className="wea-crm-table-edit">
                            {isShowPanel && <ColorPanel data ={tagValue} bgcolor={bgcolor} valuecolor={color} sureColor={this.sureColor} cancelColor={this.cancelColor} />}
                            <Table 
                                key={isrefresh}
                                columns={columns} 
                                dataSource={dataSource}
                                pagination={false}
                            />
                        </div>
                </WeaRightMenu>
            </WeaDialog>
        )
    }

    setVisible = (visible) => {
        this.setState({visible: visible})
    }

    getButtons() {
        let btnArr = [];
        btnArr.push(<Button type="primary" title={getLabel(82,"新建")} size="small" onClick={this.onAdd.bind(this)} style={{padding: "1px 4px", marginRight: "10px"
        }} ><Icon type="plus" /></Button>)
        return btnArr
    }
     onRightMenuClick(key){
    	if(key == '0'){
            this.doSave();
    	}
    	if(key == '1'){
    	}
    	if(key == '2'){
    	}
    }
    getRightMenu(){
    	let btns = [];
    	btns.push({
    		icon: <i className='icon-coms-Preservation'/>,
    		content:getLabel(86,"保存")
    	});
        btns.push({
    		icon: <i className='icon-coms-Collection2'/>,
    		content:getLabel(28111,'收藏')
    	});
        btns.push({
            icon: <i className='icon-coms-help'/>,
            content:getLabel(275,'帮助'),
        });
    	return btns
    }

    showColorPanel=(value,bgcolor,color,index)=>{
        this.setState({isShowPanel:true,tagValue:value,bgcolor:bgcolor,color:color,index:index})
    }
    sureColor=(bg,valcolor)=>{
        const {bgcolor,color,index,dataSource} = this.state;
        let _dataSource =  [].concat(dataSource);
        _dataSource[index].labelColor = bg;
        _dataSource[index].textColor= valcolor;
        this.setState({dataSource:_dataSource,isShowPanel:false});
    }

    cancelColor=()=>{
        this.setState({isShowPanel:false})
    }

    doSave=()=>{
        const {contentStore,type} = this.props;
        const {dataSource}  = this.state;
        for(const obj of dataSource){
            if(obj.title === ""){
                message.error(getLabel(15859,"必要信息不完整，红色标记为必填项！"));
                return;
            }
        }
        contentStore.crmTagEdit({tagsInfo:JSON.stringify(dataSource),type:type});
        // this.setState({visible:false,isShowPanel:false})
    }
}

export default SetTagModal